package com.ssm.demo.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.demo.entity.Person;
import com.ssm.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;
    // 接口：http://localhost:8080/ssmDemo/person/selectPerson?id=1
    @RequestMapping("/selectPerson")
    public void selectPerson(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //        中文乱码
        //        https://blog.csdn.net/zhangzuyuanbest/article/details/53453792
        //        下面两个配置未生效
        //        request.setCharacterEncoding("utf-8");
        //        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");

        long personId = Long.parseLong(request.getParameter("id"));
        Person person = personService.findPersonById(personId);

        ObjectMapper mapper = new ObjectMapper();
        //getWriter()方法将 输出编码设置成iso-8859-1，这样输出utf8编码字符串必然乱码
        response.getWriter().write(mapper.writeValueAsString(person));
        response.getWriter().close();
    }

}